//
//  JCBrightness.m
//
//  Created by HJaycee on 16/8/13.
//  Copyright © 2016年 HJaycee. All rights reserved.
//

#import "JCBrightness.h"

static CGFloat _currentBrightness;
static NSOperationQueue *_queue;
static BOOL JCBrightness_isResume;/// 当前是否是关闭的亮度调整


@implementation JCBrightness

+ (void)initialize{
    
    if (self == JCBrightness.class) {
        //系统通知：手机亮度改变时发送的通知
//        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(saveDefaultBrightness) name:UIScreenBrightnessDidChangeNotification object:nil];
        JCBrightness_isResume = false;
        [self saveDefaultBrightness];
    }
}


+ (void)saveDefaultBrightness{
    _currentBrightness = [UIScreen mainScreen].brightness;
}


+ (void)graduallySetBrightness:(CGFloat)value{

    if (!_queue) {
        _queue = [[NSOperationQueue alloc] init];
        _queue.maxConcurrentOperationCount = 1;
    }
    [_queue cancelAllOperations];
    
    //计算总时间
    CGFloat totalTime = JCBrightness_isResume ? 0.5 : 0.8;
    CGFloat spaceTime = totalTime / 50;

    CGFloat brightness = [UIScreen mainScreen].brightness;
    CGFloat step = spaceTime * ((value > brightness) ? 1 : -1);
    int times = fabs((value - brightness) / spaceTime);
    //根据亮度差计算出时间和每个单位时间调节的亮度值
    for (CGFloat i = totalTime; i < times + totalTime; i++) {
        
        [_queue addOperationWithBlock:^{
            [NSThread sleepForTimeInterval:totalTime / 50];
            [UIScreen mainScreen].brightness = brightness + i * step;
        }];
    }
    
    [_queue addOperationWithBlock:^{
        JCBrightness_isResume = false;
    }];
}


+ (void)graduallyResumeBrightness{
    JCBrightness_isResume = true;
    [self graduallySetBrightness:_currentBrightness];
}


+ (void)fastResumeBrightness{
    if (!_queue) {
        _queue = [[NSOperationQueue alloc] init];
        _queue.maxConcurrentOperationCount = 1;
    }
    [_queue cancelAllOperations];
    [_queue addOperationWithBlock:^{
        [UIScreen mainScreen].brightness = _currentBrightness;
    }];
}

@end
